package com.blue.base.oauth.server.config.authentic.handler;

import com.blue.base.oauth.common.utils.OAuthTokenUtils;
import com.blue.base.redis.utils.RedisUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author liulei
 * @version 1.0
 */
@Slf4j
@Component
public class MyLogoutHandler implements LogoutHandler {

    @Autowired
    private ConsumerTokenServices tokenServices;

    @SneakyThrows
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        Assert.notNull(tokenServices, "tokenStore must be set");
        String token = request.getParameter("accessToken");
        if (!StringUtils.isEmpty(token)) {
            tokenServices.revokeToken(token);
            RedisUtils.del(OAuthTokenUtils.generateKey());
            log.info("退出后清除token|{},refresh_token记录等", token);
        }
        String redirectUri = request.getParameter("redirect_uri");
        if (!StringUtils.isEmpty(redirectUri)) {
            response.sendRedirect(redirectUri);
        }
    }
}
